﻿// --------------------------------
// <copyright file="SharePageCoreLib.cs" company="Samaj Shekhar">
//     Copyright (c) 2010-2011 Samaj Shekhar
// </copyright>
// <author>Samaj Shekhar (samaj.shekhar@hotmail.com)</author>
// <license>Released under the terms of the Microsoft Public License (Ms-PL)</license>
// <website>http://thesharepage.codeplex.com</website>
// ---------------------------------

using System;
using System.Drawing;
using System.Text;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Web;
using System.Configuration;
using SharePage.CoreLib.Utils.ExtentionMethods;

namespace SharePage.CoreLib
{

    /// <summary>
    /// <para>A class that represents a badge for The Share Page, Similar to Facebook Badge</para>
    /// <para>It Encapsulates various methods and propertes for designing the Badge</para>
    /// <para>NOTE: This class cannot be inherited</para>
    /// </summary>
    /// <remarks>
    /// Copyright: Copyright (c) 2010-2011 Samaj Shekhar
    /// Last Update: 12-Nov-2010|11:51pm
    /// </remarks>
    public sealed class TSPBadge
    {
        /// <summary>
        /// Image for the TSP badge's title bar (Static Field)
        /// </summary>
        private static Image TSPBadgeTitleBar = Image.FromFile(@"C:\Users\SHEKHAR\Desktop\Test HTML\tsp1.png");

        /// <summary>
        /// The Default Width for TSP Badge (Constant Field)
        /// </summary>
        public const int DBadgeWidth = 300;

        /// <summary>
        /// The Default Height for TSP Badge (Constant Field)
        /// </summary>
        public const int DBadgeHeight = 500;

        /// <summary>
        /// Set this variable to true if a TSP badge has been successfully made
        /// </summary>
        public bool IsMade = false;

        /// <summary>
        /// Initializes the static members of the TSPBadge Class (Static Constructor)
        /// </summary>
        static TSPBadge()
        {
            BadgeWidth = DBadgeWidth;
            BadgeHeight = DBadgeHeight;
        }

        /// <summary>
        /// Initializes a new Instance of TSPBadge with default values
        /// </summary>
        public TSPBadge()
        {
            IsMade = false;
            UserPic = null;
            UserName = null;
            EmailID = null;
            UserStatus = null;
        }

        /// <summary>
        /// Initializes a new Instance of TSPBadge with specified Width and Height
        /// </summary>
        /// <param name="Width">The Width for the TSP Badge</param>
        /// <param name="Height">The Height for the TSP Badge</param>
        public TSPBadge(int Width, int Height)
        {
            BadgeWidth = Width;
            BadgeHeight = Height;
        }

        /// <summary>
        /// Initializes a new Instance of TSPBadge with specified Image, Name, Status and EmailID.
        /// </summary>
        /// <param name="userpic">The user's picture</param>
        /// <param name="username">The name of the user</param>
        /// <param name="emailID">The user's EmailID</param>
        /// <param name="userstatus">The user's most recent status text</param>
        public TSPBadge(Image userpic, string username, string emailID, string userstatus)
        {
            IsMade = false;
            UserPic = new Bitmap(userpic);
            UserName = username.ToUpper(CultureInfo.InvariantCulture);
            EmailID = emailID;
            UserStatus = userstatus;
        }

        /// <summary>
        /// Gets or Sets the Width to be used for drawing TSP badge. (Static Property)
        /// </summary>
        public static int BadgeWidth { get; set; }

        /// <summary>
        /// Gets or Sets the Height to be used for drawing TSP badge. (Static Property)
        /// </summary>
        public static int BadgeHeight
        {
            get
            {
                return _BadgeHeight;
            }
            set
            {
                GraphicsUnit gu = GraphicsUnit.Pixel;
                //The TSP Badge's Minimum height is the height of TSP TitleBar's height
                if (value <= (int)TSPBadgeTitleBar.GetBounds(ref gu).Height)
                {
                    _BadgeHeight = (int)TSPBadgeTitleBar.GetBounds(ref gu).Height;
                }
                else
                {
                    _BadgeHeight = value;
                }
            }
        }
        private static int _BadgeHeight;

        /// <summary>
        /// Gets or Sets the User Picture to be used for drawing TSP Badge
        /// </summary>
        public Bitmap UserPic { get; set; }

        /// <summary>
        /// Gets or Sets the User Name to be used for drawing TSP Badge
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// Gets or Sets the User EmailID to be used for drawing TSP Badge
        /// </summary>
        public string EmailID { get; set; }

        /// <summary>
        /// Gets or Sets the User's Status text to be used for TSP Badge
        /// </summary>
        public string UserStatus { get; set; }


        /// <summary>
        /// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID. (Static Method)
        /// </summary>
        /// <param name="userpic">The user's picture</param>
        /// <param name="username">The name of the user</param>
        /// <param name="emailID">The user's EmailID</param>
        /// <param name="userstatus">The user's most recent status text</param>
        /// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
        public static Bitmap MakeBadge(Image userpic, string username, string emailID, string userstatus)
        {
            Bitmap bmp = new Bitmap(BadgeWidth, BadgeHeight);
            Graphics gf = Graphics.FromImage(bmp);
            GraphicsUnit gu = GraphicsUnit.Pixel;
            string BatchString = String.Format("{0}\n\nEMAIL:  {1}\n\nSTATUS:  {2}", username.ToUpper(CultureInfo.InvariantCulture), emailID, userstatus);
            //We are taking 60% of the bitmap space for User picture - (int)((float)BadgeHeight * (60F / 100F))
            //Write status, name etc in rest of 40% bitmap space
            float PicPer = 60F;
            float RstPer = 100F - PicPer;
            gf.Clear(Color.White);
            gf.DrawImage(userpic, new Rectangle(2, 2, BadgeWidth - 4, (int)((float)BadgeHeight * (PicPer / 100F)))); //NOTE: The rectangle here takes a non-zero based width/height so 300
            gf.DrawImage(TSPBadgeTitleBar, new Rectangle(0, 0, BadgeWidth, (int)TSPBadgeTitleBar.GetBounds(ref gu).Height));
            //TODO: Insert code to check name dosen't go out of title bar and get trimmed
            gf.DrawString(username.ToUpper(CultureInfo.InvariantCulture), new Font(new FontFamily("Arial"), 10F), Brushes.White, new PointF(5, 6));
            gf.DrawRectangle(Pens.Black, 0, 0, BadgeWidth - 1, BadgeHeight - 1); //NOTE: DrawRectangle takes a 0 based width/height so 300-1
            gf.DrawRectangle(Pens.Black, 1, 1, BadgeWidth - 3, ((int)((float)BadgeHeight * (PicPer / 100F))) + 1);
            gf.DrawRectangle(Pens.Black, 1, ((int)((float)BadgeHeight * (PicPer / 100F))) + 3, BadgeWidth - 3, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5);
            gf.DrawString(BatchString, new Font(new FontFamily("Arial"), 10F), Brushes.Black, new RectangleF(5, ((int)((float)BadgeHeight * (PicPer / 100F))) + 6, BadgeWidth - 7, ((int)((float)BadgeHeight * (RstPer / 100F))) - 5), StringFormat.GenericTypographic);
            return bmp;
        }

        /// <summary>
        /// Draws a TSP Badge on bitmap.
        /// <para>NOTE: This function requires that all the requiremens are set already other wise it returns a null bitmap</para>
        /// </summary>
        /// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
        public Bitmap GetBadge()
        {
            IsMade = false;
            Bitmap bmp = null;
            if (UserPic != null && UserName != null && EmailID != null && UserStatus != null)
            {
                bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
                IsMade = true;
            }
            return bmp;
        }

        /// <summary>
        /// Draws a TSP Badge on bitmap with specified Image, Name, Status and EmailID.
        /// </summary>
        /// <param name="userpic">The user's picture</param>
        /// <param name="username">The name of the user</param>
        /// <param name="emailID">The user's EmailID</param>
        /// <param name="userstatus">The user's most recent status text</param>
        /// <returns>Returns an  TSP Badge as an Bitmap Image</returns>
        public Bitmap GetBadge(Image userpic, string username, string emailID, string userstatus)
        {
            IsMade = false;
            UserPic = new Bitmap(userpic);
            UserName = username.ToUpper(CultureInfo.InvariantCulture);
            EmailID = emailID;
            UserStatus = userstatus;
            Bitmap bmp = TSPBadge.MakeBadge(UserPic, UserName, EmailID, UserStatus);
            IsMade = true;
            return bmp;
        }
    }

    /// <summary>
    /// <para>This Class represents a base class for User like TSP User, Facebook User</para>
    /// <para>and Twitter User. It can also be directly used for representing a user</para>
    /// <para>NOTE: It is recomended to inherit this class and define your own user type</para>
    /// </summary>
    /// <remarks>
    /// Copyright: Copyright (c) 2010-2011 Samaj Shekhar
    /// Last Update: 22-Nov-2010|11:55pm
    /// </remarks>
    public class User
    {
        /// <summary>
        /// Gets or Sets the User Name
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or Sets the User's First name
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or Sets the User's Middle Name
        /// </summary>
        public string MiddleName { get; set; }

        /// <summary>
        /// Gets or Sets the User's Last Name
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// Gets or Sets the User's Date of birth
        /// </summary>
        public DateTime DateOfBirth { get; set; }

        /// <summary>
        /// <para>Holds the collection of User's EmailID in form of strings</para>
        /// <para>Use <code>Add(string value)</code> method of <code>System.Collections.Specialized.StringCollection</code> class to add emails.</para>
        /// <para>- Value: The email address</para>        
        /// </summary>
        public StringCollection EmailIDs = new StringCollection();

        /// <summary>
        /// <para>Holds the collection of User's accounts in different websites like TSP, FB, TTR etc. in form of strings</para>
        /// <para>Use <code>Add(string value)</code> method of <code>System.Collections.Specialized.StringCollection</code> class to add website names.</para>
        /// <para>- Value: The website's Domain name, like "SharePage" for http://www.thesharepage.com</para> 
        /// </summary>
        public StringCollection HasAccountsIn = new StringCollection();

        /// <summary>
        /// Initializes a new Instance of User class with default values
        /// </summary>
        public User()
        {
            Name = string.Empty;
            FirstName = string.Empty;
            MiddleName = string.Empty;
            LastName = string.Empty;
            EmailIDs = new StringCollection();
            DateOfBirth = new DateTime();
        }

        /// <summary>
        /// Initializes a new Instance of User class with given values
        /// </summary>
        /// <param name="name">User's name</param>
        public User(string name)
        {
            FirstName = string.Empty;
            MiddleName = string.Empty;
            LastName = string.Empty;
            Name = name;
            EmailIDs = new StringCollection();
            DateOfBirth = new DateTime();
        }

        /// <summary>
        /// Initializes a new Instance of User class with given values
        /// </summary>
        /// <param name="FName">User's First name</param>
        /// <param name="LName">User's Last name</param>
        public User(string FName, string LName)
        {
            FirstName = FName;
            MiddleName = string.Empty;
            LastName = LName;
            Name = string.Empty;
            EmailIDs = new StringCollection();
            DateOfBirth = new DateTime();
        }

        /// <summary>
        /// Initializes a new Instance of User class with given values
        /// </summary>
        /// <param name="FName">User's First name</param>
        /// <param name="MName">User's Middle name</param>
        /// <param name="LName">User's Last name</param>
        public User(string FName, string MName, string LName)
        {
            FirstName = FName;
            MiddleName = MName;
            LastName = LName;
            Name = string.Empty;
            EmailIDs = new StringCollection();
            DateOfBirth = new DateTime();
        }

        /// <summary>
        /// This method joins First Name, Middle Name, Lastname and gives a Full Name
        /// </summary>
        /// <returns>Returns a full name of the user</returns>
        public string FullName()
        {
            return string.Concat(FirstName.Trim() == string.Empty ? string.Empty : FirstName.Trim() + ' ', MiddleName.Trim() == string.Empty ? string.Empty : MiddleName.Trim() + ' ', LastName.Trim() == string.Empty ? string.Empty : LastName.Trim()).Trim();
        }

        /// <summary>
        /// This method joins First Name, Middle Name, Lastname and gives a Full Name (Static Method)
        /// </summary>
        /// <param name="FName">user's First name</param>
        /// <param name="MName">User's Middle name</param>
        /// <param name="LName">User's Last name</param>
        /// <returns>Returns a full name of the user</returns>
        public static string FullName(string FName, string MName, string LName)
        {
            return string.Concat(FName.Trim() == string.Empty ? string.Empty : FName.Trim() + ' ', MName.Trim() == string.Empty ? string.Empty : MName.Trim() + ' ', LName.Trim() == string.Empty ? string.Empty : LName.Trim()).Trim();
        }

        /// <summary>
        /// <para>This method creates the Initials of the User's name and returns it as a string in ALL CAPS</para>
        /// <example>For example S.S for SAMAJ SHEKHAR</example>
        /// </summary>
        /// <returns>Returns initials of the user</returns>
        public string Initials()
        {
            return string.Concat(FirstName.Trim() == string.Empty ? string.Empty : FirstName.Trim().Substring(0, 1) + '.', MiddleName.Trim() == string.Empty ? string.Empty : MiddleName.Trim().Substring(0, 1) + '.', LastName.Trim() == string.Empty ? string.Empty : LastName.Trim().Substring(0, 1)).ToUpper(CultureInfo.InvariantCulture).Trim('.');
        }

        /// <summary>
        /// <para>This method creates the Initials of the User's name and returns it as a string in ALL CAPS (Static Method)</para>
        /// <example>For example S.S for SAMAJ SHEKHAR</example>
        /// </summary>
        /// <param name="FName">user's First name</param>
        /// <param name="MName">User's Middle name</param>
        /// <param name="LName">User's Last name</param>
        /// <returns>Returns initials of the user</returns>
        public static string Initials(string FName, string MName, string LName)
        {
            return string.Concat(FName.Trim() == string.Empty ? string.Empty : FName.Trim().Substring(0, 1) + '.', MName.Trim() == string.Empty ? string.Empty : MName.Trim().Substring(0, 1) + '.', LName.Trim() == string.Empty ? string.Empty : LName.Trim().Substring(0, 1)).ToUpper(CultureInfo.InvariantCulture).Trim('.');
        }

        /// <summary>
        /// <para>This method creates a short name of the User's name and return it as a string</para>
        /// <example>For example S.Shekhar for Samaj Shekhar</example>
        /// </summary>
        /// <returns>Returns a short name of the user</returns>
        public string ShortName()
        {
            return string.Concat(
                FirstName.Trim() == string.Empty ? string.Empty : (
                    (MiddleName.Trim() == string.Empty && LastName.Trim() == string.Empty) ? FirstName.Trim() : FirstName.Trim().Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + '.'),
                MiddleName.Trim() == string.Empty ? string.Empty : (
                    LastName.Trim() != string.Empty ? MiddleName.Trim().Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + '.' : MiddleName.Trim()),
                LastName.Trim() == string.Empty ? string.Empty : LastName.Trim()).Trim('.');
        }

        /// <summary>
        /// <para>This method creates a short name of the User's name and return it as a string (Static Method)</para>
        /// <example>For example S.Shekhar for SAMAJ SHEKHAR</example>
        /// </summary>
        /// <param name="FName">user's First name</param>
        /// <param name="MName">User's Middle name</param>
        /// <param name="LName">User's Last name</param>
        /// <returns>Returns a short name of the user</returns>
        public static string ShortName(string FName, string MName, string LName)
        {
            return string.Concat(
                FName.Trim() == string.Empty ? string.Empty : (
                    (MName.Trim() == string.Empty && LName.Trim() == string.Empty) ? FName.Trim() : FName.Trim().Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + '.'),
                MName.Trim() == string.Empty ? string.Empty : (
                    LName.Trim() != string.Empty ? MName.Trim().Substring(0, 1).ToUpper(CultureInfo.InvariantCulture) + '.' : MName.Trim()),
                LName.Trim() == string.Empty ? string.Empty : LName.Trim()).Trim('.');
        }

        /// <summary>
        /// <para>This method extracts the email provider from the given email address (Static Method)</para>
        /// <example>For example hotmail for samaj.shekhar@hotmail.com</example>
        /// </summary>
        /// <param name="EmailID">User's EmailID</param>
        /// <returns>Returns the email provider as a string</returns>
        public static string EmailProvider(string EmailID)
        {
            try
            {
                return EmailID.Split('@')[1].Split('.')[0].ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// <para>This method simply returns the first email address from the Collection of email addresses</para>
        /// <para>Assuming it to be the primary email address</para>
        /// </summary>
        /// <returns>Returns the User's primary address</returns>
        public string PrimaryEmailID()
        {
            try
            {
                return EmailIDs[0].ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Calculates the age of the User from the current date.
        /// </summary>
        /// <returns>Returns the age of the user as int</returns>
        public int Age()
        {
            if (DateOfBirth != new DateTime())
            {
                return ((int)(DateTime.Now.Subtract(DateOfBirth).TotalDays / (double)365));

            }
            return -1;
        }

        /// <summary>
        /// Calculates the age of the User from the current date. (Static Method)
        /// </summary>
        /// <param name="DateOfBirth">User's date of birth</param>
        /// <returns>Returns the age of the user as int</returns>
        public static int Age(DateTime DateOfBirth)
        {
            if (DateOfBirth != new DateTime())
            {
                return ((int)(DateTime.Now.Subtract(DateOfBirth).TotalDays / (double)365));

            }
            return -1;
        }
    }


    public class TSPCookie
    {
        public static string MainCookiename = "_tsp_usr_cks";
        public static string IsNewUser = "_nuser";
        public static string SessionId = "_tsp_sid";
        public static string RememberMe = "_rem_m";
        public static string GoingForAuthorization = "_t_fbfa";
        public static string UserID = "_tsp_uid";

        public static void SetFreshUserCookie(HttpContext Context)
        {
            HttpCookie cookie = new HttpCookie(TSPCookie.MainCookiename);
            NameValueCollection cookiecollection = new NameValueCollection();
            cookiecollection.Add(TSPCookie.IsNewUser, "1");
            cookiecollection.Add(TSPCookie.SessionId, Context.Session.SessionID);
            cookiecollection.Add(TSPCookie.RememberMe, "0");
            cookiecollection.Add(TSPCookie.GoingForAuthorization, "0");
            cookiecollection.Add(TSPCookie.UserID, "0");
            cookie.Values.Add(cookiecollection);
            cookie.Expires = DateTime.Now.AddDays((double)5);            
            Context.Response.Cookies.Add(cookie);
        }
    }

    public class TSPSettings
    {
        public static string AppID
        {
            get
            {
                if (!ConfigurationManager.AppSettings["App_ID"].IsEmptyOrNull())
                {
                    return ConfigurationManager.AppSettings["App_ID"];
                }
                throw new ConfigurationErrorsException("Error in web.config Confugration, App_ID not set");
            }
        }

        public static string API_Key
        {
            get
            {
                if (!ConfigurationManager.AppSettings["API_Key"].IsEmptyOrNull())
                {
                    return ConfigurationManager.AppSettings["API_Key"];
                }
                throw new ConfigurationErrorsException("Error in web.config Confugration, API_Key not set");
            }
        }

        public static string App_Secret
        {
            get
            {
                if (!ConfigurationManager.AppSettings["App_Secret"].IsEmptyOrNull())
                {
                    return ConfigurationManager.AppSettings["App_Secret"];
                }
                throw new ConfigurationErrorsException("Error in web.config Confugration, App_Secret not set");
            }
        }

        public static string Support_Email
        {
            get
            {
                if (!ConfigurationManager.AppSettings["Support_Email"].IsEmptyOrNull())
                {
                    return ConfigurationManager.AppSettings["Support_Email"];
                }
                throw new ConfigurationErrorsException("Error in web.config Confugration, Support_Email not set");
            }
        }

        public static string Domain
        {
            get
            {
                if (!ConfigurationManager.AppSettings["Domain"].IsEmptyOrNull())
                {
                    return ConfigurationManager.AppSettings["Domain"];
                }
                throw new ConfigurationErrorsException("Error in web.config Confugration, Domain not set");
            }
        }
    }
}